﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MethodWorx.Core.Validation;
using MethodWorx.CMS.Plugins;
using StructureMap;
using MethodWorx.CMS.Membership;
using MethodWorx.CMS.Services;

namespace MethodWorx.CMS.UI.Application
{
    public class ApplicationController : Controller, IValidationProvider
    {
        public User CurrentUser { get; private set; }
        public ApplicationController()
        {

        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!this.User.Identity.IsAuthenticated)
            {
                //  always redirect
                filterContext.Result = RedirectToAction("Index", "Login");
            }
            else
            {
                this.CurrentUser =  ObjectFactory.GetInstance<IUserService>().GetUserById(Guid.Parse(this.User.Identity.Name));
            }
        }


        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            

            base.OnActionExecuting(filterContext);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        }

        protected override void HandleUnknownAction(string actionName)
        {
            //
            //  ok, we are previewing a page, which means
            //  that any url that comes in needs to be dealt with as virtual
            //  URL
            bool processed = false;
            foreach (SafePlugin plugin in ObjectFactory.GetInstance<PluginFactory>().GetRequestPlugins())
            {
                //
                //  ok, process
                processed = plugin.Invoke<IRequestPlugin, bool>(p => p.ProcessRequest(new HttpContextWrapper(System.Web.HttpContext.Current)));
                if (processed)
                    break;
            }
            if (!processed)
                base.HandleUnknownAction(actionName);
            else
            {
                System.Web.HttpContext.Current.Response.End();
            }
        }

        #region IValidationProvider Members

        public bool Validate(object instance)
        {
            return this.TryValidateModel(instance);
        }

        public void AddError(string key, string message)
        {
            this.ModelState.AddModelError(key, message);
        }

        public bool IsValid()
        {
            return this.ModelState.IsValid;
        }


        #endregion
    }
}